#include "stdafx.h"
#include "WZListFile.h"

#include "WZCrypto.h"

using namespace std;

namespace WZLib{
	const std::vector<WZStringProperty*>&		WZListFile::entries(){return this->_entries;}
	ctor WZListFile::WZListFile(string filePath,short gameVersion):WZFile(filePath){
		this->_type=ListFile;
	}
	dtor WZListFile::~WZListFile(){
		this->_entries.clear();
	}
	char WZListFile::peek(){
		char r;
		this->_reader->_fread(&r,sizeof(char),1);
		this->_reader->IncPosition(-1);
		return r;
	}
	ErrorCode WZListFile::parse(WZLib::WZBinaryReader *reader){
		if(this->_path=="")
			return Error_WZLib_WZFile_Parse_InvalidFilePath;
		reader=new WZBinaryReader(this->_path.c_str());
		if(!(reader->Opened()))
			return Error_WZLib_WZFile_Parse_InvalidFilePath;
		this->_reader=reader;
		while(peek()!=-1){
			int len=this->_reader->ReadInt32();
			if(len<0)
				break;
			char* list=new char[len];
			for(int i=0;i<len;i++)
				list[i]=(char)this->_reader->ReadInt16();
			this->_reader->ReadUInt16();
			string ds;
			for(int i=0;i<len;i++)
				ds+=(char)(list[i]^((char)((WZCrypto::WZKey[i*2+1]<<8)+WZCrypto::WZKey[i*2])));
			if(peek()==-1){
				int i=0;
				while(ds.at(ds.size()-1)=='/'){
					ds.erase(ds.size()-1,1);
					i++;
				}
				if(i!=0 && ds.at(ds.size()-1)!='g')
					ds.push_back('g');
			}
			this->_entries.push_back(new WZStringProperty(ds,NULL,ds));
		}
		reader->Close();
		return Error_NoError;
	}
};